package com.limedia.explorer.transmission;

import com.limedia.explorer.constant.Constant;

import android.util.Log;
import limedia.sdk.api.realtime.TSPcmData;

public class StreamUploader extends Thread implements Runnable {

	private static String TAG = StreamUploader.class.getSimpleName();
	private volatile boolean isRunning = true;
	
	private TSPcmData spsData = null;
	private TSPcmData ppsData = null;
	
	public StreamUploader() {
		super();
	}
	
	@Override
	public void run() {
		
		int init = 0;
		while(this.isRunning && (init = RTMPTransmissionJNI.getInstance().init("")) == 0) {
			Log.i(TAG, "RTMPTransmissionJNI: init failed");
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Log.i(TAG, "RTMPTransmissionJNI: init succeeded");
		
		while (this.isRunning) {
			TSPcmData pcmData = Constant.queueUpload.poll();
			if(null == pcmData) {
				try {
					synchronized (this) {
						this.wait();
					}
				} catch (InterruptedException e) {
					this.isRunning = false;
					e.printStackTrace();
				}
			} else {
				this.uploadData(pcmData);
			}
		}
		
		Log.i(TAG, "onExit: ");
		if(init == 1) {
			RTMPTransmissionJNI.getInstance().deinit();
		}
	}
	
	private void uploadData(TSPcmData pcmData) {
		switch (pcmData.getFrameType()) {
		case TSPcmData.FRAME_TYPE_SPS:
			if(null == this.spsData) {
				this.spsData = pcmData;
			}
			break;
		case TSPcmData.FRAME_TYPE_PPS:
			if(null == this.ppsData) {
				this.ppsData = pcmData;
				if(null != this.spsData) {
					RTMPTransmissionJNI.getInstance().writeSPSPPS(
							this.ppsData.getPcm(), this.ppsData.getSize(), this.spsData.getPcm(), this.spsData.getSize());
					this.spsData = null;
					this.ppsData = null;
				}
			}
			break;
		case TSPcmData.FRAME_TYPE_I:
			RTMPTransmissionJNI.getInstance().writeFrame(pcmData.getPcm(), pcmData.getSize(), 1, pcmData.getTimeStamp());
			break;
		case TSPcmData.FRAME_TYPE_P:
			RTMPTransmissionJNI.getInstance().writeFrame(pcmData.getPcm(), pcmData.getSize(), 0, pcmData.getTimeStamp());
			break;
		default:
			break;
		}
	}

	@Override
	public void start() {
		super.start();
	}
	
	public void stopRun() {
		this.isRunning = false;
		this.interrupt();
		try {
			this.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
